/*
 * Copyright (C) 2021 xuexiangjys(xuexiangjys@163.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package com.xuexiang.yoyo.fragment.other;

import static com.xuexiang.xutil.XUtil.getContentResolver;

import android.graphics.Color;
import android.provider.Settings;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.alibaba.fastjson.JSONObject;
import com.fcat.base.common.util.StrUtil;
import com.xuexiang.yoyo.R;
import com.xuexiang.yoyo.activity.MainActivity;
import com.xuexiang.yoyo.constant.HesAppStatic;
import com.xuexiang.yoyo.core.BaseFragment;
import com.xuexiang.yoyo.databinding.FragmentLoginBinding;
import com.xuexiang.yoyo.runenable.GuidUtil;
import com.xuexiang.yoyo.utils.CDKeyEncryptUtils;
import com.xuexiang.yoyo.utils.LogHesUtil;
import com.xuexiang.yoyo.utils.TokenUtils;
import com.xuexiang.xaop.annotation.SingleClick;
import com.xuexiang.xhttp2.XHttp;
import com.xuexiang.xhttp2.callback.SimpleCallBack;
import com.xuexiang.xhttp2.exception.ApiException;
import com.xuexiang.xpage.annotation.Page;
import com.xuexiang.xpage.enums.CoreAnim;
import com.xuexiang.xui.utils.ResUtils;
import com.xuexiang.xui.utils.ThemeUtils;
import com.xuexiang.xui.utils.XToastUtils;
import com.xuexiang.xui.widget.actionbar.TitleBar;
import com.xuexiang.xutil.app.ActivityUtils;


/**
 * 登录页面
 *
 */
@Page(anim = CoreAnim.none)
public class LoginFragment extends BaseFragment<FragmentLoginBinding> implements View.OnClickListener {

    @NonNull
    @Override
    protected FragmentLoginBinding viewBindingInflate(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, boolean attachToRoot) {
        return FragmentLoginBinding.inflate(inflater, container, attachToRoot);
    }

    @Override
    protected TitleBar initTitle() {
        TitleBar titleBar = super.initTitle()
                .setImmersive(true);
        titleBar.setBackgroundColor(Color.TRANSPARENT);
        titleBar.setTitle("");
        titleBar.setLeftImageDrawable(ResUtils.getVectorDrawable(getContext(), R.drawable.ic_login_close));
        titleBar.setActionTextColor(ThemeUtils.resolveColor(getContext(), R.attr.colorAccent));
        return titleBar;
    }

    @Override
    protected void initViews() {
        binding.etPhoneNumber.setText(HesAppStatic.getUsername());
        binding.etVerifyCode.setText(HesAppStatic.getPassword());
        LogHesUtil.lxfBlue("HesAppStatic.getUsername() "+HesAppStatic.getUsername());
        LogHesUtil.lxfBlue("HesAppStatic.getPassword() "+HesAppStatic.getPassword());
    }

    @Override
    protected void initListeners() {
        binding.btnLogin.setOnClickListener(this);
    }



    @SingleClick
    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.btn_login) {
            if (binding.etPhoneNumber.validate()) {
                if (binding.etVerifyCode.validate()) {
                    try {
                        loginByVerifyCode(binding.etPhoneNumber.getEditValue(), binding.etVerifyCode.getEditValue());
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        }
    }


    /**
     *  登录
     *
     * @param username 账号
     * @param password  密码
     */
    private void loginByVerifyCode(String username, String password) throws Exception {
       /* onLoginSuccess();*/
        if (StrUtil.isBlank(username) || StrUtil.isBlank(username.trim())) {
            XToastUtils.toast("请输入用户名");
            return;
        }
        if (StrUtil.isBlank(password) || StrUtil.isBlank(password.trim())) {
            XToastUtils.toast("请输入密码");
            return;
        }
        username = username.trim();
        password = password.trim();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("username", username);
        jsonObject.put("passwd", password);
        jsonObject.put("uuid", GuidUtil.createGUID(getContext()));
        jsonObject.put("deviceId", Settings.System.getString(getContentResolver(), Settings.System.ANDROID_ID));
        jsonObject.put("tokenValue", TokenUtils.getToken());
        try {
            LogHesUtil.lxfBlue("登录信息："+jsonObject.toJSONString());
            String param = CDKeyEncryptUtils.AESencrypt(jsonObject.toJSONString());
            String finalUsername = username;
            String finalPassword = password;
            XHttp.post("/readMeterApp/readMeterUser/login").params("readMeterUserLoginParamJSONString",param).syncRequest(false).onMainThread(true)
                    .execute(new SimpleCallBack<JSONObject>() {
                @Override
                public void onSuccess(JSONObject response) throws Throwable {
                    XToastUtils.toast("登录成功 "+response.toJSONString());
                    HesAppStatic.setUsername(finalUsername);
                    HesAppStatic.setPassword(finalPassword);
                    onLoginSuccess(response.getString("token"));
                }

                @Override
                public void onError(ApiException e) {
                    XToastUtils.toast("ApiException "+e.getMessage());
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
            XToastUtils.toast(e.toString());
        }
    }

    private void onLoginSuccess(String token) {
        if (TokenUtils.handleLoginSuccess(token)) {
            popToBack();
            ActivityUtils.startActivity(MainActivity.class);
        }
    }
    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }



}

